package com.zhglxt.oa.service.impl;

import com.google.common.collect.Maps;

import com.zhglxt.activiti.service.impl.ActTaskService;
import com.zhglxt.activiti.util.ActUtils;
import com.zhglxt.common.core.entity.sys.SysRole;
import com.zhglxt.common.core.entity.sys.SysUser;
import com.zhglxt.common.core.text.Convert;

import com.zhglxt.common.utils.DateUtils;
import com.zhglxt.common.utils.ShiroUtils;
import com.zhglxt.common.utils.uuid.UUID;
import com.zhglxt.oa.entity.Leave;
import com.zhglxt.oa.mapper.LeaveMapper;
import com.zhglxt.oa.service.ILeaveService;
import com.zhglxt.system.service.ISysRoleService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.PortUnreachableException;
import java.rmi.dgc.Lease;
import java.util.*;

/**
 * @Description 请假业务实现层
 * @Author liuwy
 * @Date 2019/9/27
 **/
@Service
public class LeaveServiceImpl implements ILeaveService {

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysRoleService roleService;

    private final Logger logger = LoggerFactory.getLogger(LeaveServiceImpl.class);

    @Override
    public List<Leave> getLeaveList(Map<String, Object> paramMap) {
        // 获取当前用户
        SysUser user = ShiroUtils.getSysUser();
        // 获取当前登录人所有角色列表
        Set<String> roleKeys = new HashSet<String>();
        roleKeys = roleService.selectRoleKeys(user.getUserId());
        List<SysRole> allRoles = roleService.selectRoleAll();
        logger.info("所有的角色是：{}", allRoles);
        logger.info("当前登录用户的角色是：{}", roleKeys);
        // 普通用户查自己的请假记录


        // 匹配用户的角色
        for (String userRoleKey : roleKeys) {
            // 所有的角色
            for (SysRole role : allRoles) {
                if (userRoleKey.equalsIgnoreCase(role.getRoleKey())) {
                    //管理权限小的数据查看权限
                    //普通用户查自己的请假记录
                    if (roleKeys.contains("common")) {//普通用户
                        paramMap.put("userId", user.getUserId());
                    }
                    // 部门经理查询所在部门的请假记录
                    if (userRoleKey.contains("dept")) {
                        paramMap.put("userId", null);
                        paramMap.put("deptId", user.getDeptId());
                    }
                    // hr及其他管理层查询所有的请假记录
                }
            }

        }

        // 查看下传入的参数--logger
        paramMap.entrySet().forEach(entry -> {
            logger.info("参数是：key:{},value:{}", entry.getKey(), entry.getValue());
        });


        List<Leave> leaveList = leaveMapper.getLeaveList(paramMap);

        List<Leave> leaves = new ArrayList<>();
        //查询请假单当前所在环节
        for (Leave leave : leaveList) {

            String procInsId = leave.getProcInsId();
            logger.info("procInsId:{}", procInsId);
            Task task = taskService.createTaskQuery().processInstanceId(procInsId).singleResult();

            logger.info("当前的任务的环节task是：{}", task);

            // procIns.get
            if (task != null) {
//                Act act=new Act();
//                act.setTask(task);
//                act.setTaskName(task.getName());
                leave.setCurrentTaskName(task.getName());
            }
            if (leave.getProcInsId() != null && task == null) {
                leave.setCurrentTaskName("任务已结束");
            }
            leaves.add(leave);
            logger.info("leave是：{}", leave);
        }
        return leaves;
    }

    /**
     * 保存请假信息
     *
     * @param paramMap
     * @return
     */
    @Transactional(readOnly = false)
    public String save(Map<String, Object> paramMap) {
        String resoult = "0";
        //获取当前用户
        SysUser user = ShiroUtils.getSysUser();
        //初始自定义业务表id
        if (!paramMap.containsKey("id")) {
            //新增保存
            // 自定义生成流程业务表之请假表的id
            paramMap.put("id", UUID.fastUUID());

            paramMap.put("createBy", user.getUserId());
            // todo
            paramMap.put("createDate", new Date());
            // todo
            paramMap.put("updateBy", user.getUserId());
            paramMap.put("updateDate", new Date());
            // todo
            paramMap.put("delFlag", 0);
            //插入数据库

            paramMap.entrySet().forEach(entry -> {
                logger.info("LeaveServiceImpl::save方法得到的参数：:key:{},value:{}", entry.getKey(), entry.getValue());
            });

            leaveMapper.insert(paramMap);

            // 启动流程,请假流程的启动
            String procDefKey = ActUtils.PD_LEAVE[0];
            String businessTable = ActUtils.PD_LEAVE[1];
            String businessId = paramMap.get("id").toString();
            String title = paramMap.get("content").toString();

            actTaskService.startProcess(procDefKey, businessTable, businessId, title,null);
            resoult = "1";
        } else {
            //请假驳回后更新请假表单操作
            paramMap.put("updateBy", user.getUserId());
            paramMap.put("updateDate", new Date());
            // 更新请假操作时的参数
            logger.info("更新请假操作时的参数");
            paramMap.entrySet().forEach(entry -> {
                logger.info("LeaveServiceIMpl::paramMap:key:{},value:{}", entry.getKey(), entry.getValue());
            });
            // 修改请假信息
            leaveMapper.update(paramMap);
            paramMap.put("act.comment", "yes".equals(paramMap.get("act.flag").toString()) ? "[重申] " : "[销毁] ");
            // 完成流程任务
            Map<String, Object> vars = Maps.newHashMap();
            // 流程任务设置变量参数，与前端的参数作比较
            vars.put("flag", "yes".equals(paramMap.get("act.flag").toString()) ? "1" : "0");
            // 完成当前任务
            actTaskService.complete(paramMap.get("act.taskId").toString(), paramMap.get("act.procInsId").toString(), paramMap.get("act.comment").toString(), paramMap.get("content").toString(), vars);
            resoult = "2";
        }
        logger.info("保存请假信息返回结果：{}", resoult);
        return resoult;
    }

    /**
     * 根据id 删除请假信息
     */
    @Override
    @Transactional
    public int updateLeaveInFoByIds(Map paramsToMap) {
        List<String> idList = Arrays.asList(paramsToMap.get("ids").toString().split(","));
        paramsToMap.put("ids", idList);
        return leaveMapper.updateLeaveInFoByIds(paramsToMap);
    }

    /**
     * 根据id 删除请假信息
     */
    @Override
    @Transactional
    public int updateLeaveInFoToList(Map paramsToMap) {
        String[] ids = paramsToMap.get("ids").toString().split(",");
        List<String> idList = Arrays.asList(ids);
        return leaveMapper.updateLeaveInFoToList(idList);
    }

    /**
     * 根据id 删除请假信息
     */
    @Override
    @Transactional
    public int updateLeaveInFoToArray(Map paramsToMap) {
        String[] idArray = Convert.toStrArray(paramsToMap.get("ids").toString());
        return leaveMapper.updateLeaveInFoToArray(idArray);
    }

    /**
     * 根据id查询请假信息
     *
     * @return
     */
    public Leave getLeaveById(Leave leave) {
        return leaveMapper.getLeaveById(leave);
    }

    /**
     * 审核审批保存
     *
     * @param leave
     * @return
     */
    @Transactional(readOnly = false)
    public int auditSave(Leave leave) {
        int i = 1;
        // 设置意见
        leave.getAct().setComment(("yes".equals(leave.getAct().getFlag()) ? "[同意] " : "[驳回] ") + leave.getAct().getComment());

        leave.preUpdate();

        // 对不同环节的业务逻辑进行操作
        String taskDefKey = leave.getAct().getTaskDefKey();

        // 提交流程变量
        Map<String, Object> vars = Maps.newHashMap();

        logger.info("auditSave方法leave参数：{}", leave);
        logger.info("auditSave方法leave.taskDefKey参数：{}", taskDefKey);
        /**
         * 处理业务信息
         */
        //更新部门经理审批意见
        if ("deptAudit".equals(taskDefKey)) {
            leave.setDeptText(leave.getAct().getComment());
            leaveMapper.updateDeptText(leave);
        }
        //更新HR审批意见
        else if ("HRAudit".equals(taskDefKey)) {
            leave.setHrText(leave.getAct().getComment());
            leaveMapper.updateHrText(leave);
            //计算请假是否大于3天
            Map<String, Object> datePoor = DateUtils.getDatePoorMap(leave.getStartTime(), leave.getEndTime());
            vars.put("day", datePoor.get("day"));

        }
        //更新总经理审批意见
        else if ("ceoAudit".equals(taskDefKey)) {
            leave.setZjlText(leave.getAct().getComment());
            leaveMapper.updateZjlText(leave);
        } else if ("xiaojia".equals(taskDefKey)) {
            leave.getAct().setComment("[同意]");
        }
        // 未知环节，直接返回
        else {
            return i;
        }
        logger.info("flag:{}", leave.getAct().getFlag());
        vars.put("flag", "yes".equals(leave.getAct().getFlag()) ? "1" : "0");
        /**
         * 完成当前任务
         */

        actTaskService.complete(leave.getAct().getTaskId(), leave.getAct().getProcInsId(), leave.getAct().getComment(), vars);
        i = 0;
        logger.info("完成当前任务：返回结果：{}", i);
        return i;
    }

}
